import { defineStore } from 'pinia';
import type { loginForm, loginResData } from '@/api/user/type';
import type { UserState } from './types/type'
import { reqLogin, reqUserInfo } from '@/api/user';
import { SET_TOKEN, GET_TOKEN } from '@/utils/token'
import { constantRoute } from '@/router/routes';

let useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      themeColor: '#409EFF',
      themeType: 'dark'
    }
  },
  actions: {
    async userLogin(data: loginForm) {
      // 登录
      let result: loginResData =  await reqLogin(data);
      if(result.code === 200){
        this.token = (result.data.token as string);
        // pinia | vuex 无法持久化存储，所以需要使用本地存储
        SET_TOKEN(result.data.token as string)
        // return Promise.resolve(result.data);
        return 'ok';
      }else{
        return Promise.reject(new Error(result.data.message));
      }
    },
    async getUserInfo(){
      let result = await reqUserInfo();
      if(result.code === 200){
        if(result.code === 200){
          this.username = result.data.checkUser.username;
          this.avatar = result.data.checkUser.avatar;
          return 'ok';
        } else {
          return Promise.reject('获取用户信息失败');
        }
      }
    }
  },
  getters: {}
})

export default useUserStore;